package com.nf.health.app.bodyfat;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.bodyfat.adapter.BodyFatHistoryDataAdapter;
import com.nf.health.app.customview.DragListView;
import com.nf.health.app.http.RequestProvider;
import com.nf.health.app.bodyfat.bean.BodyFatHistoryBean;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.ViewUtil;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by hepan on 2016/3/21.
 * The only genius that is worth anything is the genius for hard work
 * <p/>
 * 体脂数据历史记录
 */
public class BodyFatHistoryDataActivity extends BaseActivity {

    @Bind(R.id.lv_date)
    DragListView lvDate;
    @Bind(R.id.titlebar_right_tv)
    TextView titlebarRightTv;
    @Bind(R.id.tv_weight)
    TextView tvWeight;
    @Bind(R.id.tv_weight_status)
    TextView tvWeightStatus;
    @Bind(R.id.tv_fat_value)
    TextView tvFatValue;
    @Bind(R.id.tv_fat_status)
    TextView tvFatStatus;
    @Bind(R.id.tv_skeleton_value)
    TextView tvSkeletonValue;
    @Bind(R.id.tv_skeleton_status)
    TextView tvSkeletonStatus;
    @Bind(R.id.tv_water_value)
    TextView tvWaterValue;
    @Bind(R.id.tv_water_status)
    TextView tvWaterStatus;
    @Bind(R.id.tv_muscle_value)
    TextView tvMuscleValue;
    @Bind(R.id.tv_muscle_status)
    TextView tvMuscleStatus;
    @Bind(R.id.tv_viscus_fat_value)
    TextView tvViscusFatValue;
    @Bind(R.id.tv_viscus_status)
    TextView tvViscusStatus;
    @Bind(R.id.tv_heat_value)
    TextView tvHeatValue;
    @Bind(R.id.tv_heat_status)
    TextView tvHeatStatus;

    private RequestProvider provider;
    private static final String REQUEST_BODY_FAT_HISTORY = "request_body_fat_history";
    private static final String REQUEST_MORE_DATA = "request_more_data";
    private static final String DELETE_DATA = "delete_data";

    private String pageNo = "1";
    private String pageSize = "15";
    private int totalPage = 1;

    private BodyFatHistoryDataAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContent(R.layout.activity_body_fat_history_data);
        setTitleBar(R.layout.layout_common_header);
        ButterKnife.bind(this);

        initView();
        initListener();
        provider = new RequestProvider(this);
        provider.requestBodyFatHistoryData(pageNo, pageSize, REQUEST_BODY_FAT_HISTORY);
    }

    private void initListener() {
        titlebarRightTv.setOnClickListener(this);
        lvDate.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PreferenceHelper.putInt(PreferenceHelper.BODY_FAT_HISTTORY_ITEM, position);
                adapter.notifyDataSetChanged();
                //设置item对应数据
                setSelectedItemData(position);
            }
        });
    }

    /**
     * 设置数据
     *
     * @param position 点击条目位置
     */
    private void setSelectedItemData(int position) {
        //header占一个位置,这里position-1
        BodyFatHistoryBean.DataBean.DeviceDataBean deviceData = bean.data.deviceData.get(position - 1);
        tvWeight.setText(deviceData.weight + "");
        tvWeightStatus.setText(deviceData.weight_status);
        changeColor(deviceData.weight_status.equals("正常"), tvWeight, tvWeightStatus);

        tvFatValue.setText(deviceData.fat_value + "");
        tvFatStatus.setText(deviceData.fat_status);
        changeColor(deviceData.fat_status.equals("正常"), tvFatValue, tvFatStatus);

        tvSkeletonValue.setText(deviceData.skeleton_value + "");
        tvSkeletonStatus.setText(deviceData.skeleton_status);
        changeColor(deviceData.skeleton_status.equals("正常"), tvSkeletonValue, tvSkeletonStatus);

        tvWaterValue.setText(deviceData.water_value + "");
        tvWaterStatus.setText(deviceData.water_status);
        changeColor(deviceData.water_status.equals("正常"), tvWaterValue, tvWaterStatus);

        tvMuscleValue.setText(deviceData.muscle_value + "");
        tvMuscleStatus.setText(deviceData.muscle_status);
        changeColor(deviceData.muscle_status.equals("正常"), tvMuscleValue, tvMuscleStatus);

        tvViscusFatValue.setText(deviceData.viscus_fat_value + "");
        tvViscusStatus.setText(deviceData.viscus_status);
        changeColor(deviceData.viscus_status.equals("正常"), tvViscusFatValue, tvViscusStatus);

        tvHeatValue.setText(deviceData.heat_value + "");
        tvHeatStatus.setText(deviceData.heat_status);
        changeColor(deviceData.heat_status.equals("正常"), tvHeatValue, tvHeatStatus);
    }

    /**
     * 改变tv颜色
     * @param isNormal 是否正常
     * @param tvs 数组
     *
     */
    private void changeColor(boolean isNormal,TextView... tvs){
        for (int i = 0; i < tvs.length; i++) {
            if (isNormal){//正常是蓝色
                tvs[i].setTextColor(this.getResources().getColor(R.color.theme_color));
            }else{//异常时橘色
                tvs[i].setTextColor(this.getResources().getColor(R.color.theme_orange));
            }
        }
    }

    private void initView() {
        //设置标题
        ViewUtil.setText(this, R.id.titlebar_title_tv, "历史数据");
        titlebarRightTv.setVisibility(View.VISIBLE);
        ViewUtil.setText(this, R.id.titlebar_right_tv, "删除");
        lvDate.setDivider(null);

        lvDate.setRefreshableAndLoadMoreable(true, true);
        lvDate.setOnRefreshAndLoadMoreListener(new DragListView.onRefreshAndLoadMoreListener() {
            @Override
            public void onRefresh() {
                totalPage++;

                requestData(totalPage + "", pageSize, REQUEST_MORE_DATA);
            }
            @Override
            public void onLoadMore() {
                totalPage++;
                requestData(totalPage+"", pageSize,REQUEST_MORE_DATA);
            }
        });
    }

    private void requestData(String pageNo, String pageSize, String httpFlag) {
        if (provider == null) {
            provider = new RequestProvider(this);
        }
        if (REQUEST_BODY_FAT_HISTORY.equals(httpFlag)) {
            //首次请求数据
            provider.requestBodyFatHistoryData(pageNo, pageSize, REQUEST_BODY_FAT_HISTORY);
        }
        if (REQUEST_MORE_DATA.equals(httpFlag)) {
            //首次更多数据
            provider.requestBodyFatHistoryData(pageNo, pageSize, REQUEST_MORE_DATA);
        }
    }

    private BodyFatHistoryBean bean;

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        if (REQUEST_BODY_FAT_HISTORY.equals(actionName)) {
            bean = (BodyFatHistoryBean) object;
            if (adapter == null) {
                adapter = new BodyFatHistoryDataAdapter(this, bean);
            }
            lvDate.setAdapter(adapter);
            //默认显示第一条数据
            if (bean.data.deviceData.size() > 0){
                setSelectedItemData(1);
            }
        } else if (DELETE_DATA.equals(actionName)) {
            showToast("删除成功");
        } else if (REQUEST_MORE_DATA.equals(actionName)) {
            lvDate.completeRefresh();
            lvDate.completeLoadMore();
            BodyFatHistoryBean extra1 = (BodyFatHistoryBean) object;
            if (extra1 == null || extra1.data.deviceData.equals("[]") || extra1.data.deviceData.size() < 1) {
                showToast("没有更多数据");
            } else {
                bean.data.deviceData.addAll(extra1.data.deviceData);
                adapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.titlebar_right_tv:
                showDeleteDialog();
                break;
            default:
                break;
        }
    }

    /**
     * 展示删除对话框
     */
    private void showDeleteDialog() {
         new AlertDialog.Builder(this)
                .setTitle("确认")
                .setMessage("确认删除?")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteHistoryData();
                    }
                }).setNegativeButton("否",null)
                .show();

    }

    /**
     * 删除历史记录
     */
    private void deleteHistoryData() {
        //获得当前选中的位置id,1代表第0个对象,因为刷新头布局占据了lv一个位置
        int position = PreferenceHelper.getInt(PreferenceHelper.BODY_FAT_HISTTORY_ITEM, 1);

        if (bean != null && bean.data.deviceData.size() >= position){
            //获得集合中对象id
            int id = bean.data.deviceData.get(position - 1).id;
            provider.requestDeleteHistory("balance", id + "", DELETE_DATA);

            //刷新界面
            bean.data.deviceData.remove(position - 1);
            adapter.notifyDataSetChanged();
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        //重新设置选中item为1 使得初次进入时为最近数据 存1时因为draglistview有一个刷新头
        PreferenceHelper.putInt(PreferenceHelper.BODY_FAT_HISTTORY_ITEM, 1);
    }
}
